package controllers


import (
	"github.com/astaxie/beego"
	."LiquidMeasurement/forms"
	"fmt"
	//"github.com/astaxie/beego/validation"
	"time"
	."LiquidMeasurement/lib"
	m"LiquidMeasurement/models"
	"strconv"
	"LiquidMeasurement/commonControllers"
	"LiquidMeasurement/forms"
	//"github.com/astaxie/beego/validation"
"LiquidMeasurement/lib"
)

type AdminController struct {
	beego.Controller
}

/*********************************************************/
/************函数：CheckAdminIsLogin*****************/
/************功能：用于验证用户是否登入***********************/
/*********************************************************/
func (this *AdminController)CheckAdminIsLogin(userid string)(bool,AdminSessionType) {

	var mAdminSessionType AdminSessionType
		data := this.GetSession(userid)
		fmt.Println("GetSession",data)

		if data == nil{
			return false,mAdminSessionType
		}else{
			mAdminSessionType = data.(AdminSessionType)
//			fmt.Println("mAdminSessionType",mAdminSessionType)
			if mAdminSessionType.IsLogin == false{
				return false,mAdminSessionType
			}else{
				if((mAdminSessionType.LastDate.Unix() - time.Now().Unix()) > ONEDAY2SEC){
					return false,mAdminSessionType

				}else{
					return true,mAdminSessionType
				}
			}
		}

	return true,mAdminSessionType
}


func (this *AdminController)AddSession(userid string,admin m.Admin){
	data := this.GetSession(userid)
	var mAdminSessionType AdminSessionType
	if data == nil{
		mAdminSessionType.LastDate = time.Now()
		mAdminSessionType.Count = 0
		mAdminSessionType.IsLogin = true
		mAdminSessionType.Admin = admin
	}else{
		mAdminSessionType = data.(AdminSessionType)
		mAdminSessionType.IsLogin = true
		mAdminSessionType.LastDate = time.Now()
	}
	this.SetSession(userid,mAdminSessionType)
}

func (this *AdminController)GetSessionAdmin(userid string)(admin m.Admin){
	return this.GetSession(userid).(AdminSessionType).Admin
}


func (this *AdminController)DelSession(userid string){
	data := this.GetSession(userid)
	if data == nil{

	}else{
		this.DelSession(userid)
	}
}

func (this *AdminController) Get() {
	this.Ctx.Redirect(302, "/admin/login")
	return
}


/*********************************************************/
/************函数：Login********************************/
/************功能：管理员登入*******************************/
/*********************************************************/
func (this *AdminController) Index() {
	UserID := this.Ctx.Input.Param(":UserID")
	if islogin,_ := this.CheckAdminIsLogin(UserID);islogin == true {
		Id,_ :=strconv.ParseInt(UserID, 10, 64)
		model ,_:= m.GetAdminByUserID(Id)
		var monitor MonitorType
		if model.FilterDepartmentID == 0{
			monitor.DepartmentName = "所有部门"
		}else{
			dep ,_:= m.GetDepartmnetById(model.FilterDepartmentID)
			monitor.DepartmentName = dep.Name
		}
		admin := (this.GetSessionAdmin(UserID))
		departments ,_ := m.GetDepartmentList()
		rooms ,_ := m.GetRoomList()

		this.Data["departments"] = &departments
		this.Data["admin"] = &model
		this.Data["UserID"] = UserID
		this.Data["monitor"] = &monitor
		this.Data["admin"] = &admin
		this.Data["rooms"] = &rooms

		this.TplName = "show_devices.html"
		return
	}else{
		this.Ctx.Redirect(302, "/admin/login")

	}
}

/*********************************************************/
/************函数：Login********************************/
/************功能：管理员登入*******************************/
/*********************************************************/
func (this *AdminController) Login() {
	//	获取网页请求的方式
	method := this.Ctx.Input.Method()
	if method == "POST"{       //判断请求方式
		//var respone_json Reg_Log_Type
		var mLoginType = new(LoginForm)
		//this.ParseForm(&mLoginType)
		Errors := make([]lib.ERROR,0,10)
		if err := this.ParseForm(mLoginType); err == nil {
			if _, err_msg := mLoginType.CheckValid(); len(err_msg) != 0 {
				Errors = append(Errors, err_msg...)
			}else {
				if admin, err := m.GetAdminByJobID(mLoginType.JobID); err == nil {
					if admin.Passwd == Strtomd5(mLoginType.Passwd) {
						//respone_json = Reg_Log_Type{SUCCESS,admin.Id,INVALID}
						this.AddSession(strconv.FormatInt(admin.UserID, 10),admin)
						data := this.GetSession(strconv.FormatInt(admin.UserID, 10))
						fmt.Println("session", data, "id", strconv.FormatInt(admin.UserID, 10))
						if (admin.Permission == 1) {
							this.Ctx.Redirect(302, "/admin/show_admin_index/" + strconv.FormatInt(admin.UserID, 10))

						}else {
							this.Ctx.Redirect(302, "/admin/index/" + strconv.FormatInt(admin.UserID, 10))
						}
						return
						//this.ServeJSON();
					}else {
						Errors = append(Errors, lib.ERROR{0, "账号或密码错误"})
						return
					}
				}else {
					Errors = append(Errors, lib.ERROR{0, "数据库错误"})}
			}
		}
		//this.Data["admin"] = &this.GetSessionAdmin(UserID)
		this.Data["Errors"] = &Errors
		this.TplName = "admin_login.html"
	}else{
		this.TplName = "admin_login.html"

	}
}

/*********************************************************/
/************函数：LoginOut********************************/
/************功能：管理员登出*******************************/
/*********************************************************/
func (this *AdminController) LoginOut() {
	fmt.Printf("logout")
	UserID := this.Ctx.Input.Param(":UserID")
	var mAdminSessionType AdminSessionType
	data := this.GetSession(UserID)

	if data != nil {

		mAdminSessionType = data.(AdminSessionType)
		mAdminSessionType.IsLogin = false
	}
	this.Ctx.Redirect(302, "/admin/login")
	return
}

/*********************************************************/
/************函数：RegisterUser********************************/
/************功能：注册新的管理员****************************/
/*********************************************************/
func (this *AdminController) RegisterAdmin() {
	//	获取网页请求的方式
	method := this.Ctx.Input.Method()
	UserID := this.Ctx.Input.Param(":UserID")

	if islogin,_ := this.CheckAdminIsLogin(UserID);islogin == true {
		admin := (this.GetSessionAdmin(UserID))
		if method == "POST" {     //判断请求方式
			var u RegisterType
			Errors := make([]ERROR, 0, 10)
			if err := this.ParseForm(&u); err == nil {
				fmt.Println("u",u,"permision",u.Permission,"department",u.Department)
				if _, err_msg := u.CheckValid(); len(err_msg) != 0 {
					Errors = append(Errors, err_msg...)
				}else {
					if _, err := m.GetAdminByJobID(u.JobID); err == nil {

						Errors = append(Errors, ERROR{0, "该用户已经存在"})
					}else {
						department, _ := m.GetDepartmnetById(u.Department)
						user := m.Admin{UserName:u.UserName, JobID:u.JobID, Passwd:u.Passwd, Tel:u.Tel, IdentifyCard:u.IdentifyCard, Department:&department, Permission:0}

						if _, err = m.AddAdmin(&user); err != nil {
							Errors = append(Errors, ERROR{0, "存入数据库错误"})

						}else {
							this.Ctx.Redirect(302, "/admin/show_admins_list/" + strconv.FormatInt(user.UserID, 10))
							return
						}

					}
				}

				departments, _ := m.GetDepartmentList()
				this.Data["admin"] = &admin
				this.Data["UserID"] = UserID
				this.Data["departments"] = &departments
				this.Data["Errors"] = &Errors
				this.TplName = "add_admin.html"
				return

			}
		}else {
			this.Data["admin"] = &admin
			departments, _ := m.GetDepartmentList()
			this.Data["UserID"] = UserID
			this.Data["departments"] = &departments
			this.TplName = "add_admin.html"
			return
		}
	}else{
		this.Ctx.Redirect(302, "/admin/login")

	}
}

/*********************************************************/
/************函数：DeleteAdmins****************************/
/************功能：删除多个管理员的数据**************************/
/********************************************************/
func (this *AdminController)DeleteAdmins(){

}

/*********************************************************/
/************函数：DeleteAdmin***************************/
/************功能：删除单个管理员的数据**********************/
/********************************************************/
func (this *AdminController)DeleteAdmin(){
	method := this.Ctx.Input.Method()
	if method == "POST" {       //判断请求方式
		var form = new(forms.AdminCommonForms)
		//this.ParseForm(&mLoginType)
		if err := this.ParseForm(form); err != nil {
			this.Abort("401")
			return
		}
		//department := m.Department{Id:form.Id,Name:form.Name,Detail:form.Detail}
		_,err := m.DelAdminByUserID(form.UserID)
		fmt.Println("form:",form)
		if(err == nil){
			respone_json := forms.SiteResponeType{forms.SITE_SUCCESS,forms.INVALIDS,forms.INVALIDS}
			this.Data["json"] = &respone_json
			this.ServeJSON();
		}else{
			respone_json := forms.SiteResponeType{forms.SITE_DELETE_ERR,forms.INVALIDS,forms.INVALIDS}

			this.Data["json"] = &respone_json
			this.ServeJSON();
		}

		//this.TplName = "show_departments.html"
		return
	}else{
		respone_json := forms.SiteResponeType{forms.SITE_METHOD_ERROR, forms.INVALIDS, forms.INVALIDS}
		this.Data["json"] = &respone_json
		this.ServeJSON();
		return
	}

}

/*********************************************************/
/************函数：UpdateUser*****************************/
/************功能：更新管理员的数据**************************/
/********************************************************/
func (this *AdminController)UpdateAdmin(){
	method := this.Ctx.Input.Method()
	UserID := this.Ctx.Input.Param(":UserID")
	id := this.Ctx.Input.Param(":UserID")
	Id, _ := strconv.ParseInt(id, 10, 64)
	if islogin,_ := this.CheckAdminIsLogin(UserID);islogin == true {
		admin := (this.GetSessionAdmin(UserID))
		if method == "POST" {
			var form = new(forms.RegisterType)
			Errors := make([]lib.ERROR,0,10)
			if err := this.ParseForm(form); err == nil {
				if _,err_msg :=form.CheckValid();len(err_msg) != 0{
					Errors = append(Errors,err_msg...)
				}else{
					if (form.Passwd != form.RePasswd) {
						Errors = append(Errors,lib.ERROR{0,"两次密码不一致"})
					}else {


						department, _ := m.GetDepartmnetById(form.Department)
						model := m.Admin{Tel:form.Tel, UserID:form.UserID, JobID:form.JobID, Permission:form.Permission, Passwd:form.Passwd, UserName:form.UserName, Department:&department, IdentifyCard:form.IdentifyCard}
						_, err := m.UpdateAdmin(&model)

						if (err == nil) {
							this.Ctx.Redirect(302, "/admin/show_admins_list/" + UserID)
							return
						}else {
							//this.TplName = "add_room.html"
							Errors = append(Errors, lib.ERROR{0, "数据库更新错误"})
						}
					}
				}
			}
			model, _ := m.GetAdminByUserID(Id)
			departments, _ := m.GetDepartmentList()
			this.Data["admin"] = &admin
			this.Data["user"] = &model
			this.Data["departments"] = &departments
			this.Data["UserID"] = id
			this.Data["Errors"] = &Errors

			this.TplName = "update_admin.html"
			return

		}else {


			model, err := m.GetAdminByUserID(Id)
			departments, _ := m.GetDepartmentList()
			if (err == nil) {
				this.Data["admin"] = &admin
				this.Data["user"] = &model
				this.Data["departments"] = &departments
				this.Data["UserID"] = id
				this.TplName = "update_admin.html"
				return
			}else {
				this.Abort("401")
				return
			}
		}
	}else{
		this.Ctx.Redirect(302, "/admin/login")

	}
}

/*********************************************************/
/************函数：GetUser***************************/
/************功能：返回管理员*************************/
/********************************************************/
func (this *AdminController)GetUser() {
	if islogin,_ := this.CheckAdminIsLogin("");islogin == true {
		UserID := this.Ctx.Input.Param(":UserID")    //从url中提取数据
		data := this.GetSession(UserID)          //从session中提取数据
		var mAdminSessionType AdminSessionType
		if data == nil {                       //数据为空
			var admins  interface{}
			this.Data["json"] = &admins
			this.ServeJSON();
			return
		}else {
			mAdminSessionType = data.(AdminSessionType)    //数据格式转换
			if mAdminSessionType.IsLogin == false {
				var admins  interface{}
				this.Data["json"] = &admins
				this.ServeJSON();
				return
			}else {
				if ((mAdminSessionType.LastDate.Unix()-time.Now().Unix()) > ONEDAY2SEC) {
					var admins  interface{}
					this.Data["json"] = &admins
					this.ServeJSON();
					return
				}
			}
		}
		admins, _ := m.GetAdminList()
		this.Data["json"] = &admins
		this.ServeJSON();
	}else{
		this.Ctx.Redirect(302, "/admin/getuser")
		return
	}
}

/*********************************************************/
/************函数：GetAllUsers***************************/
/************功能：返回所有管理员*************************/
/********************************************************/
func (this *AdminController) GetAllUsers() {
	this.Data["Website"] = "beego.me"
	this.Data["Email"] = "astaxie@gmail.com"
	this.TplName = "index.html"
}


func (this *AdminController) ShowAdminIndex() {
	UserID := this.Ctx.Input.Param(":UserID")

	if islogin,_ := this.CheckAdminIsLogin(UserID);islogin == true {
		admin := (this.GetSessionAdmin(UserID))
		admins,_ := m.GetAdminList()
		this.Data["admins"] = &admins
		this.Data["UserID"] = UserID
		this.Data["admin"] = &admin
		this.TplName = "admin_index.html"
		return
	}else{
		this.Ctx.Redirect(302, "/admin/login")
	}
	return
}
func (this *AdminController) ShowAdminsList() {
	UserID := this.Ctx.Input.Param(":UserID")

	if islogin,_ := this.CheckAdminIsLogin(UserID);islogin == true {
		admin := (this.GetSessionAdmin(UserID))
		models, _ := m.GetAdminList()
		//fmt.Println("models",models[0].Department.Name)
		//	Errors,_ := this.Ctx.Input.Param(":UserName")
		this.Data["admins"] = &models
		this.Data["admin"] = &admin
		this.Data["UserID"] = UserID
		//	this.Data["Errors"] = Errors
		this.TplName = "admin_list.html"
		return
	}else{
		this.Ctx.Redirect(302, "/admin/login")
	}
}

/*********************************************************/
/************函数：ChangeFilter*****************************/
/************功能：更新管理员的数据**************************/
/********************************************************/
func (this *AdminController)ChangeFilter(){
	method := this.Ctx.Input.Method()
	UserID := this.Ctx.Input.Param(":UserID")

	if method == "POST" {
		var form = new(forms.ChangeFilterForm)
		if err := this.ParseForm(form); err != nil {
			this.Abort("401")
			return
		}
		beego.Info("ChangeFilter",form)
		id ,_:= strconv.ParseInt(UserID,10,64)
		admin ,_:= m.GetAdminByUserID(id)
		admin.FilterDepartmentID = form.FilterDepartmentID
		admin.FilterFloor = form.FilterFloor
		beego.Info("ChangeFilter admin",form)

		m.UpdateAdmin(&admin)

		respone_json := forms.SiteResponeType{forms.SITE_SUCCESS,forms.INVALIDS,forms.INVALIDS}

		this.Data["json"] = &respone_json
		this.ServeJSON()
		return
	}else{
		rooms ,_ := m.GetRoomList()
		departments ,_ := m.GetDepartmentList()
		this.Data["UserID"] = UserID
		this.Data["rooms"] = &rooms

		this.Data["departments"] = &departments

		this.TplName = "change_filter.html"
		return
	}

}

func (this *AdminController) BoadcastIP(){
	method := this.Ctx.Input.Method()
	//UserID := this.Ctx.Input.Param(":UserID")
	if method == "POST" {
		var form = new(TcpUdpCmd)
		if err := this.ParseForm(form); err != nil {
			fmt.Printf("err",err)
			this.Abort("401")
			return
		}
		if(form.OpCode == 1){

			commonControllers.SendInformBroadcast()
			form.RespCode = 200
			this.Data["json"] = &form
			this.ServeJSON();
		}else{
			form.RespCode = 201
			this.Data["json"] = &form
			this.ServeJSON();
		}

	}
}
func (this *AdminController) UserLogin() {
	this.TplName = "user_login.html"
	return
}
func (this *AdminController)AddUsers(){
	this.TplName = "admin_add_user.html"
	return
}